package com.yyy.dm.consumer.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yyy.dm.CommonResponse;
import com.yyy.dm.JWTUtils;
import com.yyy.dm.VoUtil;
import com.yyy.dm.consumer.feign.base.DMImageFeign;
import com.yyy.dm.dao.UserMapper;
import com.yyy.dm.user.DmUser;
import com.yyy.dm.user.LoginUserDTO;
import com.yyy.dm.user.TokenDTO;
import com.yyy.dm.user.UserInfoDTO;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserConsumerService {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private UserMapper userMapper;
    @Resource
    private DMImageFeign dmImageFeign;

    public CommonResponse sendSMS(String phoneNumber) {
        int rand = (int) ((Math.random() * 9 + 1) * 100000);
        Map<String, String> message = new HashMap<>();
        message.put("code", rand + "");
        message.put("phoneNumber", phoneNumber);
        redisTemplate.opsForValue().set("sms_" + phoneNumber, rand + "", 60L, TimeUnit.SECONDS);
        //rabbitTemplate.convertAndSend("dmsms",message);
        return VoUtil.returnSuccess(null, "短信验证码发送成功！");
    }

    public CommonResponse smsLogin(String phone, String vcode) {
        //1.没发过验证码或者已经过期都是查不到
        //2.验证码错误
        //3.正确验证查询数据库验证手机号
        //4.生成token
        String smsCode = redisTemplate.opsForValue().get("sms_" + phone);
        if (smsCode == null) {
            return VoUtil.returnFail("8888", "请获取验证码");
        }
        if (!smsCode.equals(vcode)) {
            return VoUtil.returnFail("1008", "验证码不正确");
        }
        QueryWrapper<DmUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", phone);
        DmUser dmUser = userMapper.selectOne(queryWrapper);
        if (dmUser == null) {
            return VoUtil.returnFail("7777", "用户不存在");
        }
        LoginUserDTO loginUserDTO = new LoginUserDTO();
        BeanUtils.copyProperties(dmUser, loginUserDTO);
        Map map = new ObjectMapper().convertValue(loginUserDTO, Map.class);
        String token = JWTUtils.getToken("loginUser",map);
        String extTime = 2 * 60 * 60 * 1000 + "";
        Long genTime = System.currentTimeMillis();
        return VoUtil.returnSuccess(new TokenDTO(token, extTime, genTime.toString(),loginUserDTO.getId()));
    }

    public CommonResponse code(String phoneNumber) {
        int rand = (int) ((Math.random() * 9 + 1) * 100000);
        Map<String, String> message = new HashMap<>();
        message.put("code", rand + "");
        message.put("phoneNumber", phoneNumber);
        redisTemplate.opsForValue().set("code_" + phoneNumber, rand + "", 60L, TimeUnit.SECONDS);
        //rabbitTemplate.convertAndSend("dmsms",message);
        return VoUtil.returnSuccess(null, "短信验证码发送成功！");
    }

    public CommonResponse register(String phone, String password, String vcode) {
        String smsCode = redisTemplate.opsForValue().get("code_" + phone);
        if (smsCode == null) {
            return VoUtil.returnFail("8888", "请获取验证码");
        }
        if (!smsCode.equals(vcode)) {
            return VoUtil.returnFail("1004", "验证码不正确");
        }
        QueryWrapper<DmUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", phone);
        DmUser dmUser = userMapper.selectOne(queryWrapper);
        if (dmUser != null) {
            return VoUtil.returnFail("1003", "用户已存在");
        }
        DmUser user = new DmUser();
        user.setPassword(SecureUtil.md5(password));
        user.setPhone(phone);
        user.setNickName("默认值");
        userMapper.insert(user);
        return VoUtil.returnSuccess(null, "注册成功");
    }   

    public CommonResponse login(String phone,String password){
        QueryWrapper<DmUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", phone);
        DmUser dmUser = userMapper.selectOne(queryWrapper);
        if (dmUser == null) {
            return VoUtil.returnFail("7777", "用户不存在");
        }
        if (!dmUser.getPassword().equals(SecureUtil.md5(password))){
            return VoUtil.returnFail("8888", "密码不正确");
        }
        LoginUserDTO loginUserDTO = new LoginUserDTO();
        BeanUtils.copyProperties(dmUser, loginUserDTO);
        Map map = new ObjectMapper().convertValue(loginUserDTO, Map.class);
        String token = JWTUtils.getToken("loginUser",map);
        String extTime = 2 * 60 * 60 * 1000 + "";
        Long genTime = System.currentTimeMillis();
        return VoUtil.returnSuccess(new TokenDTO(token, extTime, genTime.toString(),loginUserDTO.getId()));
    }

    public CommonResponse queryPersonInfo(Long userId){
        QueryWrapper<DmUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", userId);
        DmUser dmUser = userMapper.selectOne(queryWrapper);
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        BeanUtils.copyProperties(dmUser, userInfoDTO);
        userInfoDTO.setHeadUrl(dmImageFeign.findUserIconByUserId(userId));
        return VoUtil.returnSuccess(userInfoDTO);
    }

    public CommonResponse modifyPersonInfo(UserInfoDTO userInfoDTO, HttpServletResponse response){
        DmUser dmUser = new DmUser();
        BeanUtils.copyProperties(userInfoDTO,dmUser);
        dmUser.setUpdatedTime(LocalDateTime.now());
        userMapper.updateById(dmUser);
        LoginUserDTO loginUserDTO = new LoginUserDTO();
        BeanUtils.copyProperties(dmUser, loginUserDTO);
        Map map = new ObjectMapper().convertValue(loginUserDTO, Map.class);
        String token = JWTUtils.getToken("loginUser",map);
        response.setHeader("token",token);
        return VoUtil.returnSuccess(null,"修改成功");
    }
}
